package com.cloudfunx.common.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.SneakyThrows;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.function.Consumer;

/**
 * @author lamkeizyi
 * @version 0.0.1
 */
public class BeanCopyUtil {

    @SneakyThrows
    public static <T> T copy(Object obj, Class<T> cla) {
        if (ObjectUtils.isEmpty(obj)) return null;
        T t = cla.newInstance();
        BeanUtils.copyProperties(obj, t);
        return t;

    }

    @SneakyThrows
    public static <T> T copy(Object obj, Class<T> cla, Consumer<T> consumer) {
        if (ObjectUtils.isEmpty(obj)) return null;
        T t = cla.newInstance();
        BeanUtils.copyProperties(obj, t);
        consumer.accept(t);
        return t;

    }

    /**
     * 将原始List的内容转为另一种类型的List
     * @param sourceList  原始集合
     * @param targetClazz 需要转成的类型
     * @return 普通集合
     */
    public static <T> List<T> copy(List sourceList, Class<T> targetClazz) {
        return ListBeanUtil.convert(sourceList, targetClazz);
    }

    public static <T> Grid<T> copy(Grid<?> grid, Class<T> targetClazz) {
        return ListBeanUtil.convert(grid, targetClazz);
    }

    public static <T> Grid<T> copy(Page<?> buildPage, List<T> list) {
        return ListBeanUtil.convert(buildPage, list);
    }

    public static <T> Grid<T> copy(Page<?> buildPage, List<?> list, Class<T> cla) {
        return ListBeanUtil.convert(buildPage, list, cla);
    }

    public static <T> Grid<T> copy(IPage<?> buildPage, Class<T> cla) {
        return ListBeanUtil.convert(buildPage, cla);
    }

    @SneakyThrows
    public static <T> List<T> toSingleList(List<?> list, Class<T> clz, String methodName) {
        return ListBeanUtil.toSingleList(list, clz, methodName);
    }

    public static void copyProperties(Object source, Object target) {
        copyProperties(source, target, (String[]) null);
    }

    public static void copyProperties(Object source, Object target, String... ignoreProperties) {
        if (source == null) {
            return;
        }
        BeanUtils.copyProperties(source, target, ignoreProperties);
    }

}
